import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/exam/runningrecord/TeacherIBSpeakingController.dart';
import 'package:ichinesereader/exam/runningrecord/TeacherIBSpeakingPage.dart';
import 'package:ichinesereader/exam/runningrecord/TeacherRunningRecordController.dart';
import 'package:ichinesereader/exam/runningrecord/TeacherRunningRecordPage.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsResult.dart';
import 'package:ichinesereader/models/assessment/assessmentTeacherQueryDto.dart';
import 'package:ichinesereader/pages/teacher/evaluationRecordReview.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class AssessmentsRecordsDataGrid extends StatelessWidget {
  AssessmentsRecordsDataGrid(this.assessments, this.dto);

  List<QuestionRecord> assessments;
  AssessmentTeacherQueryDto dto;

  bool isWebOrDesktop = GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssessmentsRecordsDataGrid');

    return Expanded(child: _buildDataGrid());
  }

  Container _buildDataGrid() {
    return Container(
      width: double.infinity,
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source:
              AssessmentsRecordsDataGridSource(items: assessments, dto: dto),
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          allowSorting: true,
          allowFiltering: true,
          allowTriStateSorting: true,
          allowSwiping: false,
          isScrollbarAlwaysShown: true,
          controller: _dataGridController,
          navigationMode: GridNavigationMode.row,
          columns: <GridColumn>[
            GridColumn(
              width: 160,
              columnName: 'FirstName',
              label: buildDataGridColumnLabel('FirstName'),
            ),
            GridColumn(
              width: 160,
              columnName: 'LastName',
              label: buildDataGridColumnLabel('LastName'),
            ),
            GridColumn(
              width: 280,
              columnName: 'Title',
              label: buildDataGridColumnLabel('Task'),
            ),
            GridColumn(
              columnName: 'Status',
              width: isWebOrDesktop ? 160 : 160,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'QuestionGroup',
              visible: false,
              allowFiltering: false,
              width: isWebOrDesktop ? 10.0 : 8.0,
              label: buildDataGridColumnLabel('QuestionGroup'),
            ),
            GridColumn(
              columnName: 'Type',
              //allowFiltering: false,
              width: isWebOrDesktop ? 160 : 160,
              label: buildDataGridColumnLabel('Type'),
            ),
            GridColumn(
              columnName: 'SummaryLevel',
              allowFiltering: false,
              width: 140,
              visible: true,
              label: buildDataGridColumnLabel('Suggestions'),
            ),
            GridColumn(
              columnName: 'SummaryChange',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Suggestion'),
            ),
            GridColumn(
              columnName: 'SubmitDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('SubmitDate'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
            GridColumn(
              width: 120,
              visible: false,
              columnName: 'UserName',
              label: buildDataGridColumnLabel('UserName'),
            ),
            GridColumn(
              columnName: 'QuestionRecordId',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('QuestionRecordId'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssessmentsRecordsDataGridSource extends DataGridSource {
  AssessmentsRecordsDataGridSource(
      {required List<QuestionRecord> items,
      required AssessmentTeacherQueryDto dto}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'Title', value: dataGridRow.name),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status!.toUpperCase()),
              DataGridCell<String>(
                  columnName: 'QuestionGroup',
                  value: dataGridRow.questionGroup!.title),
              DataGridCell<String>(
                columnName: 'Type',
                value: dataGridRow.type,
              ),
              DataGridCell<int>(
                columnName: 'SummaryLevel',
                value: dataGridRow.summaryLevel,
              ),
              DataGridCell<String>(
                columnName: 'SummaryChange',
                value: dataGridRow.summaryChange,
              ),
              DataGridCell<int>(
                columnName: 'SubmitDate',
                value: dataGridRow.submittedTime,
              ),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'QuestionRecordId',
                  value: dataGridRow.questionRecordId),
            ]))
        .toList();
  }

  AssessmentTeacherQueryDto dto =
      new AssessmentTeacherQueryDto(status: [], type: []);

  List<DataGridRow> dataGridRows = [];
  final ReportsController _reportsController = ReportsController();
  final box = Hive.box('appconfig');

  @override
  List<DataGridRow> get rows => dataGridRows;

  void _downloadReport(String fileId) async {
    //String dir = (await getApplicationDocumentsDirectory()).path;
    try {
      _reportsController.downloadGradeReport(fileId).then((fileResult) {
        if (fileResult.result != null && fileResult.result?.fileLink != null) {
          launchInWebViewWithJavaScript(
              _reportsController.gradeReport.value.result!.fileLink!);
        }
      });
      // Future.delayed(Duration(milliseconds: 3000), (() async {
      //   launchInWebViewWithJavaScript(
      //       _reportsController.gradeReport.value.result!.fileLink!);

      //   // if ((GetPlatform.isAndroid || GetPlatform.isIOS) &&
      //   //     !GetPlatform.isWeb) {
      //   //   if (_reportsController.gradeReport.value.result != null) {
      //   //     await FlutterDownloader.enqueue(
      //   //       url: _reportsController
      //   //           .gradeReport.value.result!.fileLink!, // file url
      //   //       savedDir: '$dir/',
      //   //       fileName: 'gradeReport',
      //   //       saveInPublicStorage: true,
      //   //     );
      //   //   }
      //   // } else {
      //   //   launchInWebViewWithJavaScript(
      //   //       _reportsController.gradeReport.value.result!.fileLink!);
      //   // }
      //   print("Download successfully");
      // }));
    } catch (e) {
      print("eerror :::: $e");
    }
  }

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'SubmitDate') {
            if (dataGridCell.value != null && dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 6.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.black),
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.fade,
                  ));
            }
          } else if (dataGridCell.columnName == 'SummaryLevel') {
            var text = "--";
            if (dataGridCell.value != null) {
              text = "L" + dataGridCell.value.toString();
            }
            var change = row
                .getCells()
                .where((element) => element.columnName == 'SummaryChange')
                .first
                .value;
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Row(children: [
                  change != null
                      ? (change == "down"
                          ? Icon(Icons.arrow_downward_rounded)
                          : change == "stay"
                              ? Icon(Icons.equalizer_rounded)
                              : Icon(Icons.arrow_upward_rounded))
                      : Text(''),
                  Text(
                    text,
                    overflow: TextOverflow.fade,
                  )
                ]));
          } else if (dataGridCell.columnName == 'Status') {
            var text = dataGridCell.value == "COMPLETED"
                ? "Graded"
                : dataGridCell.value == "SUBMITTED"
                    ? "New"
                    : dataGridCell.value;
            var questionRecordId = row
                .getCells()
                .where((element) => element.columnName == 'QuestionRecordId')
                .first
                .value;
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Row(children: [
                  GestureDetector(
                      onTap: () {
                        var type = row
                            .getCells()
                            .where((element) => element.columnName == 'Type')
                            .first
                            .value;
                        var userName = row
                            .getCells()
                            .where(
                                (element) => element.columnName == 'UserName')
                            .first
                            .value;
                        var id = row
                            .getCells()
                            .where((element) => element.columnName == 'Id')
                            .first
                            .value;
                        var status = row
                            .getCells()
                            .where((element) => element.columnName == 'Status')
                            .first
                            .value;
                        var title = row
                            .getCells()
                            .where((element) =>
                                element.columnName == 'QuestionGroup')
                            .first
                            .value;
                        var mode = '';

                        if (GetPlatform.isAndroid || GetPlatform.isIOS) {
                          if (type.contains("IBDP")) {
                            // Get.to(() => InAppWebViewAppAssessmentGradeScreen(
                            //     type: type,
                            //     userName: userName,
                            //     id: id,
                            //     questionRecordId: questionRecordId,
                            //     dto: dto));
                            Get.lazyPut(() => TeacherIBSpeakingController());
                            Get.to(() => TeacherIBSpeakingPage(
                                assessmentId: id,
                                questionRecordId: questionRecordId,
                                status:status,
                                studentName: userName))?.then((value) {
                              ReportsController _reportsController = Get.find();
                              var classId = box.get(
                                  CacheManagerKey['currentclass'].toString());
                              _reportsController.fetchTeacherAssessmentRecords(
                                  classId, dto);
                            });
                          } else if (type == 'RUNNING_RECORD') {
                            Get.lazyPut(() => TeacherRunningRecordController());
                            Get.to(() => TeacherRunningRecordPage(
                                assessmentId: id,
                                questionRecordId: questionRecordId,
                                studentName: userName))?.then((value) {
                              ReportsController _reportsController = Get.find();
                              var classId = box.get(
                                  CacheManagerKey['currentclass'].toString());
                              _reportsController.fetchTeacherAssessmentRecords(
                                  classId, dto);
                            });
                            // Get.to(() => InAppWebViewAppAssessmentGradeScreen(
                            //     type: type,
                            //     userName: userName,
                            //     id: id,
                            //     questionRecordId: questionRecordId,
                            //     dto: dto));
                          } else if (type == 'BENCHMARK_TEST') {
                            AssessmentsController _assessmentController =
                                Get.find();
                            mode = 'evaluation';

                            if (status == 'COMPLETED') {
                              _assessmentController
                                  .fetchAssessmentRecordGrading(
                                      questionRecordId);
                            }
                            box.put('evaluationRecordLevel', 1);
                            _assessmentController
                                .fetchAssessmentRecordInfoDetails(
                                    questionRecordId);
                            Get.to(() => EvaluationRecordReviewPage(),
                                arguments: {
                                  'title': title,
                                  'status': status,
                                  'recordId': questionRecordId,
                                  'userName': userName,
                                  'assessmentType': type
                                })?.then((value) {
                              if (value != null && value['isRefresh'] == true) {
                                var classId = box.get(
                                    CacheManagerKey['currentclass'].toString());
                                if (mode == 'evaluation') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController
                                      .fetchTeacherAssessmentRecords(
                                          classId, dto);
                                } else if (mode == 'quickReview') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController
                                      .fetchLibraryRecords(classId);
                                } else if (mode == 'quizBook') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController.getQuizBookRecordsByClass(
                                      classId, "", "", "");
                                }
                              }
                            });
                          } else {
                            mode = '';
                            // to add code for dealing with other tests
                          }
                        } else {
                          if (type == "RUNNING_RECORD") {
                            // link = '${Constants.BaseURL}running-record/teacher/$id/$questionRecordId/$userName';
                            // launchInWebViewWithJavaScript(link);
                            Get.lazyPut(() => TeacherRunningRecordController());
                            Get.to(() => TeacherRunningRecordPage(
                                assessmentId: id,
                                questionRecordId: questionRecordId,
                                studentName: userName))?.then((value) {
                              ReportsController _reportsController = Get.find();
                              var classId = box.get(
                                  CacheManagerKey['currentclass'].toString());
                              _reportsController.fetchTeacherAssessmentRecords(
                                  classId, dto);
                            });
                          } else if (type.contains("IBDP")) {
                            // link =
                            //     '${Constants.BaseURL}icr/teacher/iboral/$id/$userName/$questionRecordId';
                            // launchInWebViewWithJavaScript(link);
                            Get.lazyPut(() => TeacherIBSpeakingController());
                            Get.to(() => TeacherIBSpeakingPage(
                                assessmentId: id,
                                questionRecordId: questionRecordId,
                                status: status ,
                                studentName: userName))?.then((value) {
                              ReportsController _reportsController = Get.find();
                              var classId = box.get(
                                  CacheManagerKey['currentclass'].toString());
                              _reportsController.fetchTeacherAssessmentRecords(
                                  classId, dto);
                            });
                          } else if (type == 'BENCHMARK_TEST') {
                            AssessmentsController _assessmentController =
                                Get.find();
                            mode = 'evaluation';

                            if (status == 'COMPLETED') {
                              _assessmentController
                                  .fetchAssessmentRecordGrading(
                                      questionRecordId);
                            }
                            box.put('evaluationRecordLevel', 1);
                            _assessmentController
                                .fetchAssessmentRecordInfoDetails(
                                    questionRecordId);
                            Get.to(() => EvaluationRecordReviewPage(),
                                arguments: {
                                  'title': title,
                                  'status': status,
                                  'recordId': questionRecordId,
                                  'userName': userName,
                                  'assessmentType': type
                                })?.then((value) {
                              if (value != null && value['isRefresh'] == true) {
                                var classId = box.get(
                                    CacheManagerKey['currentclass'].toString());
                                if (mode == 'evaluation') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController
                                      .fetchTeacherAssessmentRecords(
                                          classId, dto);
                                } else if (mode == 'quickReview') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController
                                      .fetchLibraryRecords(classId);
                                } else if (mode == 'quizBook') {
                                  ReportsController _reportsController =
                                      Get.find();
                                  _reportsController.getQuizBookRecordsByClass(
                                      classId, "", "", "");
                                }
                              }
                            });
                          } else {
                            mode = '';
                            // to add code for dealing with other tests
                          }
                        }
                      },
                      child: Text(
                        text,
                        softWrap: true,
                        overflow: TextOverflow.fade,
                        style: Get.textTheme.titleLarge,
                      )),
                  dataGridCell.value == "COMPLETED"
                      ? GestureDetector(
                          onTap: () {
                            _downloadReport(questionRecordId);
                          },
                          child: Icon(Icons.download))
                      : Text(''),
                ]));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 6.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall?.copyWith(
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Colors.black),
                ));
          }
        }).toList());
  }
}
